﻿using System.Configuration;
using System.Linq;

namespace System
{
    /// <summary>
    /// 配置类
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 修改设置项
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetConfig(string key, string value)
        {
            var tempConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var conf = tempConfig.AppSettings.Settings[key];
            if (conf == null)
                tempConfig.AppSettings.Settings.Add(key, value);
            else
                conf.Value = value;
            tempConfig.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 修改设置项
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Remove(string key)
        {
            var tempConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (tempConfig.AppSettings.Settings.AllKeys.Contains(key))
            {
                tempConfig.AppSettings.Settings.Remove(key);
                tempConfig.Save();
                ConfigurationManager.RefreshSection("appSettings");
            }
        }

        /// <summary>
        /// 获取设置项
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfig(string key)
        {
            var conf = ConfigurationManager.AppSettings[key];
            return conf ?? string.Empty;
        }

    }
}
